package jiang.app.realm;

import java.util.List;

import jiang.app.entity.Role;
import jiang.app.entity.User;
import jiang.app.service.UserService;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MySQLRealm extends AuthorizingRealm {
	private static Logger logger = Logger.getLogger(MySQLRealm.class);

	@Autowired
	UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {
		// TODO Auto-generated method stub
		logger.info("Realm: 授权");
		long userId = (long) p.getPrimaryPrincipal();
		List<Role> roles = userService.findRolesByUserId(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		for(Role r : roles){
			info.addRole(r.getRole());
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken t)
			throws AuthenticationException {
		// TODO Auto-generated method stub
		logger.info("Realm: 认证");
		String username = (String) t.getPrincipal();
		String password = new String((char[]) t.getCredentials());
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		User user = userService.findUserByUsernameAndPassword(u);
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getUserId(), user.getPassword(), getName());
		return authenticationInfo;
	}
}
